package com.igoal.entity;

import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.compass.annotations.SearchableProperty;
import org.springframework.security.GrantedAuthority;

@Entity
@Table(name = "role")
@NamedQueries({
        @NamedQuery(
                name = "findRoleByName",
                query = "select r from Role r where r.name = :name "
        )
})
public class Role extends BaseObject implements Serializable, GrantedAuthority, Audit {
    private static final long serialVersionUID = 3690197650654049848L;
    private Long id;
    private String name;
    private String description;
    private Date createDate;
	private Date updateDate;
	private DataStatus status;
    
	private Set<UserRole> userRoles = new HashSet<UserRole>(0);
    private Set<User> users = null;

    /**
     * Default constructor - creates a new instance with no values set.
     */
    public Role() {
    }

    /**
     * Create a new instance and set the name.
     *
     * @param name name of the role.
     */
    public Role(final String name) {
        this.name = name;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    /**
     * @return the name property (getAuthority required by Acegi's GrantedAuthority interface)
     * @see org.springframework.security.GrantedAuthority#getAuthority()
     */
    @Transient
    public String getAuthority() {
        return getName();
    }

    @Column(length = 20)
    public String getName() {
        return this.name;
    }

    @Column(length = 64)
    public String getDescription() {
        return this.description;
    }

    public void setId(Long id) {
        this.id = id;
    }
    
//    @ManyToMany(fetch = FetchType.EAGER)
//	@JoinTable(name = "user_role", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = @JoinColumn(name = "user_id"))
//    public Set<User> getUsers() {
//		return users;
//	}

//	public void setUsers(Set<User> users) {
//		this.users = users;
//	}

	public void setName(String name) {
        this.name = name;
    }

    public void setDescription(String description) {
        this.description = description;
    }
    
	/**
     * {@inheritDoc}
     */
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Role)) {
            return false;
        }

        final Role role = (Role) o;

        return !(name != null ? !name.equals(role.name) : role.name != null);

    }

    /**
     * {@inheritDoc}
     */
    public int hashCode() {
        return (name != null ? name.hashCode() : 0);
    }

    /**
     * {@inheritDoc}
     */
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.SIMPLE_STYLE)
                .append(this.name)
                .toString();
    }

    /**
     * {@inheritDoc}
     */
    public int compareTo(Object o) {
        return (equals(o) ? 0 : -1);
    }
    
    @Enumerated(EnumType.STRING)
	@Column(nullable=false, name="status")
	@SearchableProperty
	public DataStatus getStatus() {
		return status;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(nullable=false, name="mdate")
	public Date getUpdateDate() {
		return updateDate;
	}

	public void setCreateDate(Date date) {
		this.createDate = date;
	}

	public void setStatus(DataStatus dataStatus) {
		this.status = dataStatus;
	}

	public void setUpdateDate(Date date) {
		this.updateDate = date;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(nullable = false, name = "cdate")
	public Date getCreateDate() {
		return createDate;
	}

	@OneToMany(fetch=FetchType.LAZY, mappedBy="pk.role")
	public Set<UserRole> getUserRoles() {
		return userRoles;
	}

	public void setUserRoles(Set<UserRole> userRoles) {
		this.userRoles = userRoles;
	}
	
	@Transient
	public Set<User> getUsers() {
		users = new HashSet<User>(0);
		for(UserRole userRole : userRoles){
			users.add(userRole.getUser());
		}
		return users;
	}	
}

